package com.wjy.common.request.validate;

import com.wjy.common.exception.BusinessException;
import com.wjy.common.request.filter.RequestFilter;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author ybxxszl
 * @desc 验证登录
 * @date 2019/4/17
 */
@Component
@Log4j2
@Aspect
public class ValidateLogin {

    @Autowired
    private RequestFilter requestFilter;

    @Pointcut(value = "within(@org.springframework.stereotype.Controller *)")
    public void validateLoginController() {

    }

    @Pointcut(value = "within(@org.springframework.web.bind.annotation.RestController *)")
    public void validateLoginRestController() {

    }

    @Pointcut(value = "validateLoginController()||validateLoginRestController()")
    public void validateLogin() {

    }

    @Around(value = "validateLogin()")
    public Object doLoginValidate(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = proceedingJoinPoint.getSignature();
        log.info("IP: {}, Port: {}, URI: {}, Method: {}", request.getRemoteAddr(), request.getServerPort(),
                request.getRequestURI(), request.getMethod());
        log.info("Class: {}, Method: {}, Args: {}", signature.getDeclaringTypeName(), signature.getName(),
                Arrays.toString(proceedingJoinPoint.getArgs()));

        boolean flag = requestFilter.filter(request);

        if (!flag) {
            log.error("REFUSE: " + request.getRequestURI());
            throw new BusinessException("重新登录");
        }

        return proceedingJoinPoint.proceed();
    }

}
